﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Net;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.IO;


namespace AzureDriverExplorer_Client
{
    /// <summary>
    /// Interaction logic for VHDDownload.xaml
    /// </summary>
    public partial class VHDBackupDelete : Page
    {

        VHDBlob blobBackup;
        WebClient webClient;
        bool SelectedOutPath = false;
        bool CanceledUpload = false;
        string AccountName = string.Empty;
        string AccountKey = string.Empty;
        private Const cons = new Const();
        System.Resources.ResourceManager ResManager;
        //Azure
        private static GetListVHD.AzureDriveExplorerServiceSoapClient list = new GetListVHD.AzureDriveExplorerServiceSoapClient();

        string AzurePath = string.Empty;

        public VHDBackupDelete()
        {
            InitializeComponent();
            AddConnectionLanguage();
            this.pictureBoxLoading.Image = Properties.Resources.reload1;
           

            try
            {
                if (!File.Exists(Const.FileConfig))
                { File.Create(Const.FileConfig); }
                else
                {
                    try
                    {
                        // Create an instance of StreamReader to read from a file.
                        // The using statement also closes the StreamReader.
                        using (StreamReader sr = new StreamReader(Const.FileConfig))
                        {
                            String line;
                            // Read and display lines from the file until the end of 
                            // the file is reached.
                            List<VHDDataConfig> ListConfig = new List<VHDDataConfig>();
                            while ((line = sr.ReadLine()) != null)
                            {
                                try
                                {
                                    string[] vecListConfig = line.Split(' ');
                                    VHDDataConfig GetListConfig = new VHDDataConfig(vecListConfig[0], vecListConfig[1], vecListConfig[2], vecListConfig[3]);

                                    ListConfig.Add(GetListConfig);
                                }
                                catch { }
                            }
                            ListConnectionConfig.ItemsSource = ListConfig;
                        }
                    }
                    catch (Exception ex)
                    {
                        // Let the user know what went wrong.
                        MessageBox.Show(ex.Message, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);

                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message + "[" + (Const.FileConfig) + "]", string.Empty, MessageBoxButton.OK, MessageBoxImage.Error); }

        }

        /// <summary>
        ///  Menu  Language
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListViewAzureMenu_Opened(object sender, RoutedEventArgs e)
        {
            ResManager = new System.Resources.ResourceManager("AzureDriverExplorer_Client.Properties.Resources", this.GetType().Assembly);

            ContextMenu Menu = (ContextMenu)sender;
            MenuItem item1 = (MenuItem)Menu.Items[0];
            MenuItem item2 = (MenuItem)Menu.Items[1];

            item1.Header = ResManager.GetString("Backup" + cons.Language).Trim();
            item2.Header = ResManager.GetString("Delete" + cons.Language).Trim();

        }
        private void AddConnectionLanguage()
        {

            ResManager = new System.Resources.ResourceManager("AzureDriverExplorer_Client.Properties.Resources", this.GetType().Assembly);


            Bytes.Header = ResManager.GetString("Bytes" + cons.Language).Trim();
            VHDName.Content = ResManager.GetString("VHDName" + cons.Language).Trim();

            TitleConecction.Text = ResManager.GetString("Connection" + cons.Language).Trim();
            ConnectionAccountName.Text = ResManager.GetString("AccountName" + cons.Language).Trim();
            ConnectionAccountKey.Text = ResManager.GetString("AccountKey" + cons.Language).Trim();

            BtConnection.Content = ResManager.GetString("Connection" + cons.Language).Trim();
            BtClear.Content = ResManager.GetString("Clear" + cons.Language).Trim();
            BtCancelar.Content = ResManager.GetString("Cancel" + cons.Language).Trim();

            DataAccountName.Header = ResManager.GetString("AccountName" + cons.Language).Trim();
            DataContainerName.Header = ResManager.GetString("ContainerName" + cons.Language).Trim();
            DataVHDName.Header = ResManager.GetString("VHDName" + cons.Language).Trim();
            GetAdd.Content = ResManager.GetString("Add" + cons.Language).Trim();
            GetCancel.Content = ResManager.GetString("Cancel" + cons.Language).Trim();

            BackupVHD.Text = ResManager.GetString("BackupVHD" + cons.Language).Trim();
            txtFile.Content = ResManager.GetString("SelectOutPath" + cons.Language).Trim();

            StartBuckup.Content = ResManager.GetString("Start" + cons.Language).Trim();
            Cancel_backup.Content = ResManager.GetString("Cancel" + cons.Language).Trim();

        }

        private void Connection_Click(object sender, RoutedEventArgs e)
        {
            if (!Validate())
                return;

            popupLoad.Visibility = Visibility.Visible;
            

            System.Threading.Thread threadImage = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
           {
               //this.pictureBoxLoading.Image = Properties.Resources.reload1;
               //this.popupLoad.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
               //{
               //    popupLoad.Visibility = Visibility.Visible;
                   
               //}));
           }));
            threadImage.Start();

            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
            {


                //this.pictureBoxLoading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                //{
                //    //this.pictureBoxLoading.Image =  new BitmapImage(new Uri("reload1.gif",UriKind.Relative));
                //    this.pictureBoxLoading.Image = Properties.Resources.reload1;
                //}));

                System.Threading.Thread.Sleep(3000);

                LoadAccount();

            }));
            thread.Start();
        }

        private void LoadAccount()
        {

            //listFile.Items.Clear();

            // Use the storage emulator.
            CloudStorageAccount account = null;
            var filesList = new List<string>();

            try
            {
                Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
               {

                   account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + txtAccountName.Text + ";AccountKey=" + txtAccountKey.Password);

                   this.AccountName = txtAccountName.Text;
                   this.AccountKey = txtAccountKey.Password;
               }));
                // Create the Blob service client.
                CloudBlobClient client = account.CreateCloudBlobClient();

                List<VHDBlob> listblob = new List<VHDBlob>();

                foreach (Microsoft.WindowsAzure.StorageClient.CloudBlobContainer str in client.ListContainers())
                {

                    CloudBlobDirectory topLevelDirectory = client.GetBlobDirectoryReference(str.Uri.ToString());

                    IEnumerable<IListBlobItem> blobItems = topLevelDirectory.ListBlobs();
                    foreach (IListBlobItem blobItem in blobItems)
                    {
                        long size = ((CloudBlob)blobItem).Properties.Length;

                        if (System.IO.Path.GetExtension(blobItem.Uri.AbsolutePath.ToString().ToUpper()).Equals(".VHD") || System.IO.Path.GetExtension(blobItem.Uri.AbsolutePath.ToString().ToUpper()).Equals(""))
                        {

                            VHDBlob blobInfo = new VHDBlob(blobItem.Uri.AbsolutePath.ToString().ToUpper(), blobItem.Uri.AbsoluteUri, size);
                            listblob.Add(blobInfo);
                        }
                    }
                }

                this.ListConnection.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.ListConnection.ItemsSource = listblob;
            }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ResManager.GetString("Error" + cons.Language).Trim() + ": " + ex.Message, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);
            }


            ReturnColorAfter();


            this.popupConnection.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.popupConnection.Visibility = Visibility.Hidden;
            }));


            this.popupLoad.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.popupLoad.Visibility = Visibility.Collapsed;
            }));
        }

        private void ShowPopupConnection(object sender, RoutedEventArgs e)
        {
            popupConnection.Visibility = Visibility.Visible;

        }

        private void Cancel_Connection_Click(object sender, RoutedEventArgs e)
        {
            popupConnection.Visibility = Visibility.Hidden;
        }


        /// <summary>
        /// Clear textbox
        /// </summary>
        private void clear()
        {
            this.txtAccountName.Text = "";
            this.txtAccountKey.Password = "";
        }

        /// <summary>
        /// valudate data for get list VHD
        /// </summary>
        /// <returns></returns>
        private bool Validate()
        {
            bool validate = true;
            this.txtAccountName.Text = this.txtAccountName.Text.Trim();
            this.txtAccountKey.Password = this.txtAccountKey.Password.Trim();

            if (this.txtAccountName.Text.Equals(string.Empty))
            {
                this.txtAccountName.BorderBrush = Brushes.Red;
                validate = false;
            }
            if (this.txtAccountKey.Password.Equals(string.Empty))
            {
                this.txtAccountKey.BorderBrush = Brushes.Red;
                validate = false;
            }
            return validate;
        }

        /// <summary>
        /// return color original 
        /// </summary>
        private void ReturnColor()
        {
            this.txtAccountName.BorderBrush = Brushes.AliceBlue;
            this.txtAccountKey.BorderBrush = Brushes.AliceBlue;
        }

        /// <summary>
        /// return color original with under prosess
        /// </summary>
        private void ReturnColorAfter()
        {
            this.txtAccountName.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.txtAccountName.BorderBrush = Brushes.AliceBlue;
            }));
            this.txtAccountKey.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                this.txtAccountKey.BorderBrush = Brushes.AliceBlue;
            }));


        }


        /// <summary>
        /// Clear connection box
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Clear_Connection_Click(object sender, RoutedEventArgs e)
        {
            clear();
            ReturnColor();
        }


        /// <summary>
        /// Open Dialog for select folder to backup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtFile_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog ofd = new System.Windows.Forms.FolderBrowserDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtFile.Content = ofd.SelectedPath;
                if (ofd.SelectedPath.Length > 0)
                {
                    SelectedOutPath = true;
                    ReturnColorBackup();
                }
            }
        }

        /// <summary>
        /// show form for backup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BackupMenu_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menu = sender as MenuItem;
            VHDBlob VHDBlobClick = menu.DataContext as VHDBlob;

            blobBackup = new VHDBlob(VHDBlobClick.Name, VHDBlobClick.Path, VHDBlobClick.Size);


            popupBackup.Visibility = Visibility.Visible;

        }


        /// <summary>
        /// hidden form for backup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cancel_backup_Click(object sender, RoutedEventArgs e)
        {
            popupBackup.Visibility = Visibility.Hidden;
            SelectedOutPath = false;
            ReturnColorBackup();
        }

        private void StartBackup_Click(object sender, RoutedEventArgs e)
        {

            if (!ValidateBackup())
                return;

            Enable(false);
            this.ProgressGrid.Visibility = Visibility.Visible;
            string[] name = blobBackup.Name.ToString().Split('/');
            webClient = new WebClient();
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

            webClient.DownloadFileAsync(new Uri(blobBackup.Path.ToString()), txtFile.Content + "\\" + name[name.Length - 1]);


        }
        private void ReturnColorBackup()
        {
            this.txtFile.BorderBrush = Brushes.AliceBlue;
        }

        private bool ValidateBackup()
        {
            bool validate = true;

            if (!SelectedOutPath)
            {
                this.txtFile.BorderBrush = Brushes.Red;
                validate = false;
            }
            return validate;
        }

        private void Enable(bool enable)
        {

            txtFile.IsEnabled = enable;
            StartBuckup.IsEnabled = enable;
            Cancel_backup.IsEnabled = enable;
        }

        private void Cancel_Download_Click(object sender, RoutedEventArgs e)
        {
            webClient.CancelAsync();
            Enable(true);
            CanceledUpload = true;
        }

        /// <summary>
        /// Progress Backup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            ProgressBackup.Value = e.ProgressPercentage;
            txtProgress.Text = ProgressBackup.Value.ToString() + "%";

        }

        /// <summary>
        /// Completed download
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Completed(object sender, AsyncCompletedEventArgs e)
        {
            if (!CanceledUpload)
                MessageBox.Show(ResManager.GetString("Completed" + cons.Language).Trim(), string.Empty, MessageBoxButton.OK, MessageBoxImage.Information);
            this.ProgressGrid.Visibility = Visibility.Hidden;
            txtProgress.Text = "";
            Enable(true);

            CanceledUpload = false;
        }

        private GridViewColumnHeader _CurSortCol = null;
        private SortAdorner _CurAdorner = null;

        /// <summary>
        /// ListViewLocalのshort
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SortLocalClick(object sender, RoutedEventArgs e)
        {

            GridViewColumnHeader column = sender as GridViewColumnHeader;
            string field = column.Tag as string;

            if (_CurSortCol != null)
            {
                AdornerLayer.GetAdornerLayer(_CurSortCol).Remove(_CurAdorner);
                ListConnection.Items.SortDescriptions.Clear();
            }

            ListSortDirection newDir = ListSortDirection.Ascending;
            if (_CurSortCol == column && _CurAdorner.Direction == newDir)
                newDir = ListSortDirection.Descending;
            else
                newDir = ListSortDirection.Ascending;


            _CurSortCol = column;
            _CurAdorner = new SortAdorner(_CurSortCol, newDir);
            AdornerLayer.GetAdornerLayer(_CurSortCol).Add(_CurAdorner);
            ListConnection.Items.SortDescriptions.Add(new SortDescription(field, newDir));
        }

        /// <summary>
        /// ListViewAzureのshort
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SortAzureClick(object sender, RoutedEventArgs e)
        {

            GridViewColumnHeader column = sender as GridViewColumnHeader;
            string field = column.Tag as string;

            if (_CurSortCol != null)
            {
                AdornerLayer.GetAdornerLayer(_CurSortCol).Remove(_CurAdorner);
                ListConnection.Items.SortDescriptions.Clear();
            }

            ListSortDirection newDir = ListSortDirection.Ascending;
            if (_CurSortCol == column && _CurAdorner.Direction == newDir)
                newDir = ListSortDirection.Descending;
            else
                newDir = ListSortDirection.Ascending;


            _CurSortCol = column;
            _CurAdorner = new SortAdorner(_CurSortCol, newDir);
            AdornerLayer.GetAdornerLayer(_CurSortCol).Add(_CurAdorner);
            ListConnection.Items.SortDescriptions.Add(new SortDescription(field, newDir));
        }

        private void Close_popupVHDBackupDelete_Click(object sender, RoutedEventArgs e)
        {
            this.Visibility = Visibility.Hidden;
        }

        private void DeleteMenu_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBoxResult.No == MessageBox.Show(ResManager.GetString("Info_DeleteFile" + cons.Language).Trim(), "", MessageBoxButton.YesNo, MessageBoxImage.Question))
            { return; }

            popupLoad.Visibility = Visibility.Visible;

           
                //popupLoad.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                //{
                //    popupLoad.Visibility = Visibility.Visible;

                //}));
                //System.Threading.Thread.Sleep(1000);

            


            MenuItem menu = sender as MenuItem;
            VHDBlob VHDBlobClick = menu.DataContext as VHDBlob;

            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
            {
            try
            {

                string[] InfoVHD = VHDBlobClick.Path.Split('/');

                string error = list.DeleteDriver(AccountName, AccountKey, InfoVHD[3], InfoVHD[4], Const.key());
               
                if (error.Length > 0)
                    MessageBox.Show(ResManager.GetString("Error_AzureError" + cons.Language).Trim() + ": " + error, "", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                    ListConnection.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                    {
                        List<VHDBlob> DeleteItem = new List<VHDBlob>();
                        foreach (VHDBlob item in ListConnection.ItemsSource)
                            DeleteItem.Add(item);

                        DeleteItem.RemoveAt(ListConnection.SelectedIndex);
                        ListConnection.ItemsSource = DeleteItem;
                        
                    }));
                    
                    //Connection_Click(sender, e);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "", MessageBoxButton.OK, MessageBoxImage.Error);
                //Connection_Click(sender, e);
            }
            finally
            {
                //System.Threading.Thread.Sleep(2000);
                // Stop Thread
                //thread.Abort();
                popupLoad.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                   {
                       popupLoad.Visibility = Visibility.Collapsed;
                   }));
            }
            }));
            thread.Start();

        }

        private void popupGetDataFile_Click(object sender, RoutedEventArgs e)
        {
            popupGetDataFile.Visibility = Visibility.Visible;
        }

        private void Close_popupGetDataFile_Click(object sender, RoutedEventArgs e)
        {
            popupGetDataFile.Visibility = Visibility.Hidden;
        }

        private void Add_popupGetDataFile_Click(object sender, RoutedEventArgs e)
        {
            if (ListConnectionConfig.SelectedItem == null)
            {
                MessageBox.Show(ResManager.GetString("Info_Select_Data_List" + cons.Language).Trim(), string.Empty, MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            VHDDataConfig GetDataConfig = ListConnectionConfig.SelectedItem as VHDDataConfig;
            txtAccountName.Text = GetDataConfig.AccountName;
            txtAccountKey.Password = GetDataConfig.AccountKey;


            popupGetDataFile.Visibility = Visibility.Hidden;
        }

    }
}
